#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#define N 32
#define M 256

#define L 0x1//登录
#define C 0x2//聊天
#define Q 0x3//退出
typedef struct{
	int type;//消息类型
	char name[N];
	char text[M];//消息正文
}MSG;
#define LEN sizeof(MSG)
#define err_log(log)\
	do{\
	perror(log);\
	exit(1);\
	}while(0)
typedef struct sockaddr SA;
int main(int argc, const char *argv[])
{
	
	int sockfd;
	struct sockaddr_in serveraddr;
	socklen_t len=sizeof(SA);
	bzero(&serveraddr,len);
	MSG msg;
	pid_t pid;
	if(argc!=3)
	{
		fprintf(stderr,"user:%s ip port",argv[0]);
		return -1;
    }

	if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)//创建数据报套接字
	{
		err_log("fail to socket:");
	}
    
	//指定服务器的网络信息
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr=inet_addr(argv[1]);

	puts("====================client login=================");
	//msg.type=L;
	//puts("input name>>>");
	//fgets(msg.name,N,stdin);
	//msg.name[strlen(msg.name)-1]='\0';
	sendto(sockfd,&msg,LEN,0,(SA*)&serveraddr,len);//发送登录信息给服务器

	pid=fork();
	if(pid<0)
	{
		err_log("fail to fork:");
	}
	else if(pid==0)//子进程发送信息
	{
			while(1)
			{
				fgets(msg.text,M,stdin);
				msg.text[strlen(msg.text)-1]='\0';
				if(strncmp(msg.text,"quit",4)==0)//退出
				{
						msg.type=Q;
						sendto(sockfd,&msg,LEN,0,(SA*)&serveraddr,len);
						close(sockfd);
						kill(getppid(),SIGKILL);//杀死父亲
						exit(0);//自杀

				}
				else//聊天
				{
					msg.type=C;
					sendto(sockfd,&msg,LEN,0,(SA*)&serveraddr,len);
				}
			}
	}
	else //父进程接受信息
	{
			while(1)
			{
				recvfrom(sockfd,&msg,LEN,0,(SA*)&serveraddr,&len);
				printf("%s\n",msg.text);
			}
	}



	return 0;
}
